﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Text;

namespace Gqq.Csharpindepth.Common
{
    public class FileProcess
    {
        public static IEnumerable<string> GetContents(string path)
        {
            return GetContents(path, Encoding.UTF8);
        }

        public static IEnumerable<string> GetContents(string path, Encoding ed)
        {
            //            using (StreamReader sr = new StreamReader(path, ed))
            //            {
            //                yield return sr.ReadLine();
            //            }
            return GetContents(() => new StreamReader(path, ed));
        }

        /// <summary>
        /// 传入一个委托，这样让StreamReader的构建更加灵活。
        /// </summary>
        /// <param name="f"></param>
        /// <returns></returns>
        public static IEnumerable<string> GetContents(Func<StreamReader> f)
        {
            using (StreamReader sr = f())
            {
                yield return sr.ReadLine();
            }
        }

        public static void WriteFile(string content, bool append = true)
        {
//            Debug.Assert(ConfigurationSettings.AppSettings != null, "ConfigurationSettings.AppSettings != null");
            //这个方法已经过期了。ConfigurationSettings这个类。
//            var path = ConfigurationSettings.AppSettings["LogPath"];
            var path=ConfigurationManager.AppSettings["LogPath"];
            if (string.IsNullOrWhiteSpace(path))
                throw new Exception("请配置路径LogPath");
            path = Path.Combine(path, string.Format("log_{0}.log", DateTime.Today.ToString("yyyyMMdd")));
            WriteFile(content, path, Encoding.UTF8, append);
        }

        public static void WriteFile(string content, string path, bool append = true)
        {
            WriteFile(content, path, Encoding.UTF8, append);
        }

        public static void WriteFile(string content, string path, Encoding encoding, bool append = true)
        {
            if (string.IsNullOrWhiteSpace(path))
                throw new Exception("没有路径");
            using (StreamWriter sw = new StreamWriter(path, append, encoding))
            {
                sw.WriteLine(content);
            }
        }

      

        public static void Test()
        {
            GqqLog.WriteLog("读取文章开始");
            var infos = GetContents(@"f:\VIFM\我的文章\我的战术.txt", Encoding.GetEncoding("gb2312"));
            foreach (var info in infos)
            {
                Console.WriteLine(info);
            }
            GqqLog.WriteLog("读取文章结束");
        }
    }
}
